package com.yc.ueditor;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.yc.annotation.AnonymousAccess;
import com.yc.storage.service.IQiniuService;
import com.yc.util.FileUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/ueditor")
@RequiredArgsConstructor
public class UEditorController {

    @Value("${qiniu.domain}")
    private String qiniuDomain;

    private final IQiniuService qiniuService;


    @AnonymousAccess
    @RequestMapping(value = "/config")
    public void config(HttpServletRequest request, HttpServletResponse response, String action, MultipartFile file) throws IOException {
        if (action.equals("config")) {
            response.setContentType("text/javascript");
            String rootPath = request.getSession().getServletContext().getRealPath("/");
            String exec = new ActionEnter(request, rootPath).exec();
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } else if (action.contains("upload")) {
            String realName = file.getOriginalFilename();
            String extension = FileUtil.getExtensionName(realName);
            String fileType = FileUtil.getFileType(extension);

            String md5Str = SecureUtil.md5(file.getInputStream());
            String fileName = md5Str + "." + extension;
            String path = fileType + File.separator + fileName;

            qiniuService.uploadFile(file.getInputStream(), path);
            String url = qiniuDomain + path;
            //ueditor要求返回格式
            Map<String, Object> map = new HashMap<>();
            //state成功必须返回SUCCESS
            map.put("state", "SUCCESS");
            //图片地址，/ueditor/jsp/config.json配置中配置的图片前缀为"",所以这里返回完成地址
            map.put("url", url);
            map.put("title", fileName);
            map.put("original", fileName);
            map.put("type", extension);
            map.put("size", file.getSize());

            //返回json
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setHeader("Access-Control-Allow-Origin", "*");
            try (PrintWriter out = response.getWriter()) {
                out.append(JSONUtil.toJsonStr(map));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
